'use strict';

const Controller = require('egg').Controller,
  utils = require('../utils/utils'),
  moment = require('moment'),
  redisKey = require('../utils/redis_key'),
  _ = require('lodash');

class MockController extends Controller {
  // 抽奖
  async luckdraw() {
    const ctx = this.ctx;
    try {
      this.ctx.validate({
        campaign_id: 'string',
        user_id: 'string'
      }, this.ctx.request.body)

      let body = this.ctx.request.body

      let campaign = await this.ctx.app.model.Campaign.findOne({
        _id: body.campaign_id
      });

      let campaignAwards = campaign.awards.filter(item => {
        if (item.remain > 0 && item.enabled) {
          return true;
        }
      });

      let awardIds = []
      let rate = []
      let totalRate = 0;
      let emptyRate = 0;
      let empty = 'nothing'
      if (!campaignAwards || campaignAwards.length === 0) {
        throw new Error('empty awards');
      }
      campaignAwards.map((item) => {
        totalRate += item.probability
        awardIds.push(item._id)
        rate.push(item.probability)
      })

      // 未中奖概率
      if (totalRate < 100) {
        emptyRate = 100 - totalRate
        awardIds.push(empty)
        rate.push(emptyRate)
      }


      let id = utils.luck(awardIds, rate, 1)
      if (id[0] === 'nothing') {
        return this.ctx.body = {
          code: 0,
          data: {
            name: 'nothing',
            type: 'nothing'
          },
          msg: '很遗憾，没有抽中'
        }
      }

      // let plainCampaignAwards = JSON.parse(JSON.stringify(campaignAwards))
      // 奖品
      let singleAward = _.filter(campaignAwards, function (v) {
        return v._id == id[0]
      })
      let realAward = await this.ctx.app.model.Award.findOne({_id: id[0]})

      // 更新库存
      await this.ctx.app.model.Campaign.update({
        '_id': body.campaign_id,
        'awards._id': id[0],
      }, {
        $inc: {'awards.$.remain': -1}
      });

      let prizeObj = {
        campaign_id: campaign._id,
        campaign_name: campaign.title,
        grant_time: new Date(),
        award_id: id,
        award_name: singleAward[0].name, // 奖品名称
        award_type: realAward.type, // 奖品类型
        award_unit_price: realAward.unit_price, // 奖品单价
        award_quantities: 1, // 奖品数量

        // status: prizeStatus, // 发放状态 00 未发放 10 发放中 20 发放成功 30 发放失败

        user_id: body.user_id, // 用户id
      }

      let prizeStatus = '00'
      if (singleAward[0].type == '4') {
        prizeStatus = '20'
      }

      prizeObj.status = prizeStatus;

      // 创建一条中奖记录
      let prize = new this.ctx.app.model.Prize(prizeObj)
      await prize.save()

      this.ctx.body = {
        code: 0,
        data: {
          name: realAward.name,
          type: realAward.type,
          unit_price: realAward.unit_price,
          quantities: 1
        }
      }
    } catch (e) {
      ctx.body = {
        code: 1,
        msg: `${e.message}`,
      };
      ctx.logger.error(e);
    }
  }

  // 提现
  async cash() {
    const ctx = this.ctx;
    try {
      ctx.validate({
        campaign_id: 'string',
        user_id: 'string'
      }, ctx.request.body)

      const body = ctx.request.body;

      let campaign = await ctx.app.model.Campaign.findById(body.campaign_id);
      if (!campaign) {
        throw new Error('没有这个活动!');
      }
      // 查询当前限额值大小
      const redisKeyRateLimit = redisKey.rateLimit(body.campaign_id);
      let dailyLimit = await ctx.app.redis.get(redisKeyRateLimit);
      if (!dailyLimit) {
        // 设置key 设置过期时间
        await this.ctx.app.redis.set(redisKeyRateLimit, parseFloat(campaign.daily_limit.toFixed(2)))
        let end = Math.floor(new Date(moment().add(1, 'days').format('YYYY-MM-DD 00:00:00')).getTime() / 1000)
        await this.ctx.app.redis.expireat(redisKeyRateLimit, end)
        dailyLimit = campaign.daily_limit
      } else {
        dailyLimit = parseFloat(parseFloat(dailyLimit).toFixed(2))
      }

      let user = await ctx.app.model.User.findById(body.user_id)

      let prize = await ctx.app.model.Prize.aggregate([{
        $match: {
          status: {$in: ['00', '30']},
          award_type: '1',
          user_id: this.ctx.app.__mongoose.Types.ObjectId(body.user_id),
          campaign_id: this.ctx.app.__mongoose.Types.ObjectId(body.campaign_id)
        }
      }, {
        $group: {
          _id: {user_id: '$user_id', campaign_id: '$campaign_id'},
          total: {$sum: '$award_unit_price'}
        }
      }])

      let amount = prize.length > 0 ? parseFloat(prize[0].total.toFixed(2)) : 0

      // 金额大于某个值才可以提现
      if (amount <= 0) {
        return this.ctx.body = {
          code: 1,
          msg: '金额大于0才可以提现'
        }
      }

      // 限额值小于0
      if (dailyLimit < amount) {
        return this.ctx.body = {
          code: 1,
          msg: '今日限额已用尽，请改日再来'
        }
      }
      // 更新值
      await ctx.app.redis.incrbyfloat(redisKeyRateLimit, - amount)
      // let end = Math.floor(new Date(moment().add(1, 'days').format('YYYY-MM-DD 00:00:00')).getTime() / 1000)
      // await ctx.app.redis.expireat(redisKeyRateLimit, end) // 重新设置ttl

      let prizes = await ctx.app.model.Prize.find({
        status: {$in: ['00', '30']},
        award_type: '1',
        user_id: body.user_id,
        campaign_id: body.campaign_id
      })

      let prizeIds = prizes.map(item => item._id)

      // 提交兑换申请，减去占用金额
      let exchange = new ctx.app.model.Exchange({
        user_id: body.user_id,
        amount: amount,
        status: '10',
        prizes: prizeIds
      })
      await exchange.save()

      // 发起代付
      let ret = await ctx.app.pay.pay({
        orderId: exchange._id,
        sysCode: 'activity',
        amount: amount,
        productCode: 'HD_' + campaign.pcode,
        name: user.realname,
        idCardNo: user.id_card,
        bankCardNo: user.banklist[0].card_number,
        bindMobile: user.banklist[0].bind_phone_number
      })
      this.ctx.coreLogger.info(ret)
      if (ret.code === 1) {
        return ctx.body = {
          code: 1,
          msg: ret.msg
        }
      }

      // 创建支付信息
      let payment = new ctx.app.model.Payment({
        pay_merchant_code: 'activity',
        product_code: 'HD_' + campaign.pcode,
        ref_id: exchange._id,
        user_id: user._id,
        bank_card_no: user.banklist[0].card_number,
        bank_name: user.banklist[0].bank_name,
        phone_number: user.banklist[0].bind_phone_number,
        realname: user.realname,
        id_card: user.id_card,
        pay_type: '52',
        pay_seq: '',
        amount: amount,
        pay_status: '30',

        campaign_id: campaign._id,
        campaign_name: campaign.title
      })

      await payment.save()

      // 更新prize 状态
      await ctx.app.model.Prize.updateMany({
        _id: {$in: prizeIds}
      }, {
        status: '10',
        update_time: new Date()
      })

      this.ctx.body = {
        code: 0,
        msg: '提现成功，请注意银行卡收账'
      }
    } catch (e) {
      ctx.body = {
        code: -1,
        msg: `${e.message}`,
      };
      ctx.logger.error(e);
    }
  }
}

module.exports = MockController;
